//
//  AppDelegate.m
//  ZhongWangYuan
//
//  Created by ZJ on 2018/6/2.
//  Copyright © 2018年 ZJ. All rights reserved.
//

#import "AppDelegate.h"
#import "ZJTabBarController.h"
#import <PLVVodSDK/PLVVodSDK.h>
#import "YBLoginViewController.h"
#import "AppUpdateViewController.h"
#import "MyViewController.h"
#import "ElectiveViewController.h"
#import "YBElectiveViewController.h"
#import "SubjectViewController.h"
#import "HomeMenuViewController.h"
@interface AppDelegate ()<AppUpdateViewControllerDelegate,UITabBarControllerDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self initPolyvSettings];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    AppUpdateViewController *vc = [AppUpdateViewController new];
    vc.delegate = self;
    UINavigationController * mainNav = [[UINavigationController alloc]initWithRootViewController:vc];
    mainNav.navigationBar.hidden = YES;
    
    self.window.rootViewController = mainNav;
    [self.window makeKeyAndVisible];
    /**  修改状态栏字体颜色  */
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    return YES;
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if ([viewController isKindOfClass:[HomeMenuViewController class]]) {
        return YES;
    }else if ([viewController isKindOfClass:[YBElectiveViewController class]]) {
        return [self isLoging];
    }else if ([viewController isKindOfClass:[SubjectViewController class]]) {
        return  [self isLoging];
    }else if ([viewController isKindOfClass:[MyViewController class]]) {
        return [self isLoging];
    }
    return YES;
}

- (BOOL)isLoging{
    if (YBUSERINFOMODEL.studentId.length > 0) {
        return YES;
    }else{//未登录
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"请先登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            YBLoginViewController *vc = [YBLoginViewController new];
            [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [[ToolClass getMainNavigationController] presentViewController:alertController animated:YES completion:nil];
        
        return NO;
    }
}

#pragma mark - 保利威视
- (void)initPolyvSettings{
    NSString *appKey = @"Cq5RRhkjoK5IhucEAlCcq2xKA7yIguTAg2g0LRXWdnEcp5hTYrsKFrls8XsFMoKsnYzRcu4292JjLVw7AIFyOdlkiN9sa6lCFECxdHHrv58TmRJvgOF7PDYXUq03WNyxeVQWCrsk3WMTwFUSWSFJNA==";
    PLVVodSettings *settings = [PLVVodSettings settingsWithConfigString:appKey key:@"VXtlHmwfS2oYm0CZ" iv:@"2u9gDPKdX6GyQJKU" error:nil];

}


#pragma mark - AppUpdateViewControllerDelegate(检测App更新) 协议方法
- (void)AppUpdateViewControllerDeleGate_showWithIsWelcomeIn:(BOOL)isWelcomeIn{
    
    [self changeWindowRootControllerWithIsWelcomeIn:isWelcomeIn];
}
- (void)changeWindowRootControllerWithIsWelcomeIn:(BOOL)isWelcomeIn{
    UINavigationController * mainNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    NSMutableArray *controllers = [NSMutableArray arrayWithArray:mainNav.viewControllers];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"] || ![[NSUserDefaults standardUserDefaults] objectForKey:@"username"]) {
        YBLoginViewController *rootViewController = [YBLoginViewController new];
//        rootViewController.delegate = self;
        controllers[0] =rootViewController;
        [mainNav setViewControllers:controllers];
        mainNav.navigationBar.hidden = YES;
        self.window.rootViewController = mainNav;
        [self.window makeKeyAndVisible];
    }else{
        /**  自动登录  */
        [self autoLoginWithIsWelcomeIn:isWelcomeIn];
    }
    
    //引导页gif展示
    //    [self.introductionView showOnViewController:rootViewController];
    
}

-(void)autoLoginWithIsWelcomeIn:(BOOL)isWelcomeIn{
    if (isWelcomeIn) {
        [YJProgressHUD showMessage:@"数据同步中" duration:30 view:[UIApplication sharedApplication].keyWindow];
    }
    [YBRequestManager request_loginWithUsername:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"] password:[[NSUserDefaults standardUserDefaults] objectForKey:@"password"] successBlock:^(id object) {
        if (isWelcomeIn) {
            [YJProgressHUD hide];
        }
        if ([object[@"code"] integerValue] == 1) {
            if ([object[@"data"][@"result"] integerValue] == 1) {
                [self rememberUserInfoWithDic:object[@"data"]];
                UINavigationController * mainNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                
                NSMutableArray *controllers = [NSMutableArray arrayWithArray:mainNav.viewControllers];
                ZJTabBarController *zj = [[ZJTabBarController alloc] init];
                zj.delegate = self;
                controllers[0] =zj;
                [mainNav setViewControllers:controllers];
                mainNav.navigationBar.hidden = YES;
                self.window.rootViewController = mainNav;
                [self.window makeKeyAndVisible];
            }
            else{
                
                [self pleaseReLogin];
            }
        }
        else{
            [self pleaseReLogin];
        }
        
    } failBlock:^(id object) {
        if (isWelcomeIn) {
            [YJProgressHUD hide];
        }
        UINavigationController * mainNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        
        NSMutableArray *controllers = [NSMutableArray arrayWithArray:mainNav.viewControllers];
        ZJTabBarController *zj = [[ZJTabBarController alloc] init];
        zj.delegate = self;
        controllers[0] =zj;
        [mainNav setViewControllers:controllers];
        mainNav.navigationBar.hidden = YES;
        self.window.rootViewController = mainNav;
        [self.window makeKeyAndVisible];
    }];
}


-(void)pleaseReLogin{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"loginUser"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"sessionId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"username"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"password"];
    [YJProgressHUD showMessage:@"用户数据获取失败，请重新登录" inView:[UIApplication sharedApplication].keyWindow afterDelayTime:2.f];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UINavigationController * mainNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        YBLoginViewController *loginVC = [YBLoginViewController new];
        [mainNav pushViewController:loginVC animated:YES];
        
        NSMutableArray *controllers = [NSMutableArray arrayWithArray:mainNav.viewControllers];
        ZJTabBarController *rootViewController = [ZJTabBarController new];
        rootViewController.delegate = self;
        controllers[0] =rootViewController;
        [mainNav setViewControllers:controllers];
        mainNav.navigationBar.hidden = YES;
        self.window.rootViewController = mainNav;
        [self.window makeKeyAndVisible];
    });
}


-(void)rememberUserInfoWithDic:(NSDictionary *)dic{
    [[NSUserDefaults standardUserDefaults] setObject:dic[@"token"] forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:dic[@"loginUser"] forKey:@"loginUser"];
    [[NSUserDefaults standardUserDefaults] setObject:dic[@"loginUser"][@"sessionId"] forKey:@"sessionId"];
}


#pragma mark - 横竖屏切换
//此方法会在设备横竖屏变化的时候调用
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    
    //   NSLog(@"方向  =============   %ld", _allowRotate);
    if (_allowRotate == 1) {
        return UIInterfaceOrientationMaskAll;
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
}


// 返回是否支持设备自动旋转
- (BOOL)shouldAutorotate
{
    if (_allowRotate == 1) {
        return YES;
    }
    return NO;
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
